package com.graduation.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.graduation.ucenter.mapper.UserMapper;
import com.graduation.ucenter.model.dto.AuthParamsDto;
import com.graduation.ucenter.model.dto.UserDto;
import com.graduation.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2023/2/24 10:37
 */
@Slf4j
@Component
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //1.将字符串转换为AuthParamsDto
        AuthParamsDto authParamsDto;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求");
        }
        //获取认证类型
        String authType = authParamsDto.getAuthType();
        //根据认证类型从spring容器取出指定的bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        UserDto userDto = authService.execute(authParamsDto);
        UserDetails userPrincipal = getUserPrincipal(userDto);
        return userPrincipal;
    }

    /**
     * @param userDto
     * @return
     */
    public UserDetails getUserPrincipal(UserDto userDto) {
        String password = userDto.getPassword();
        //权限
        String[] authorities = {"test"};
        //根据用户id查询用户的权限
        List<String> permissions = userMapper.selectPermissionByUserId(userDto.getId());
        authorities = permissions.toArray(new String[0]);


        userDto.setPassword(null);
        //将用户信息转json
        String userJson = JSON.toJSONString(userDto);
        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();
        return userDetails;
    }
}
